package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"news-hub/cache"
	"news-hub/model"
	"strconv"
	"time"
)

func GoodOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
		   SELECT
		good_orders.id as OrderId,
		goods.good_code as GoodCode,
		goods.good_name as GoodName,
		goods.good_price as GoodPrice,
		good_orders.good_from as GoodFrom,
		good_orders.good_to as GoodTo
		FROM good_orders
		LEFT JOIN goods ON goods.id=good_orders.gid
	*/
	var list []model.GoodOrderList
	redis_key := "redis_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id as OrderId",
				"goods.good_code as GoodCode",
				"goods.good_name as GoodName",
				"goods.good_price as GoodPrice",
				"good_orders.good_from as GoodFrom",
				"good_orders.good_to as GoodTo",
			).
			Joins("LEFT JOIN goods ON goods.id=good_orders.gid").
			Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var count int64
	model.DB.Model(&model.GoodOrder{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	})

}

func GoodAdd(c *gin.Context) {
	good_code := c.PostForm("good_code")
	good_name := c.PostForm("good_name")
	good_price, _ := strconv.Atoi(c.PostForm("good_price"))
	if good_code == "" || good_name == "" || good_price == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Good{
		GoodCode:  good_code,
		GoodName:  good_name,
		GoodPrice: good_price,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func GoodOrderAdd(c *gin.Context) {
	good_from := c.PostForm("good_from")
	good_to := c.PostForm("good_to")
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	data := model.GoodOrder{
		Gid:      gid,
		GoodFrom: good_from,
		GoodTo:   good_to,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
